# main.py
import os
import sys
import asyncio
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from contextlib import asynccontextmanager
from common.postgres import PostgresManager
from common.logger import logger
from router.chat import chat_router
from conf.config import settings
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from common import register_static_file

if sys.platform == "win32":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    try:
        # 创建PostgresManager实例并设置到app.state
        postgres_manager = PostgresManager(
            dsn=settings.DB_URI,
            min_size=settings.POSTGRES_MIN_SIZE,
            max_size=settings.POSTGRES_MAX_SIZE,
            timeout=settings.POSTGRES_TIMEOUT,
        )
        
        # 初始化数据库连接
        await postgres_manager.setup()
        
        # 设置到FastAPI应用状态中
        app.state.postgres_manager = postgres_manager
        
        logger.info("🚀 应用启动完成")
        yield
    except Exception as e:
        logger.error(f"❌ 应用启动失败: {e}")
        raise
    finally:
        # 清理资源
        if hasattr(app.state, 'postgres_manager'):
            await app.state.postgres_manager.close()
        logger.info("🛑 应用已关闭")

# 创建FastAPI应用
app = FastAPI(
    title=settings.TITLE,
    description=settings.DESC,
    version=settings.VERSION,
    lifespan=lifespan
)


# 配置 Jinja2 模板
templates = Jinja2Templates(directory="templates")

# 注册路由
app.include_router(chat_router, prefix="/api/v1", tags=["graph"])


# 初始化静态文件
register_static_file(app)

@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
    """渲染聊天界面主页"""
    return templates.TemplateResponse("chat.html", {"request": request})

@app.get("/")
async def root():
    """健康检查端点"""
    return {"message": "FastGraph API is running", "status": "healthy"}

@app.get("/health")
async def health_check():
    """详细健康检查"""
    try:
        if hasattr(app.state, 'postgres_manager'):
            await app.state.postgres_manager.check_health()
            return {"status": "healthy", "database": "connected"}
        else:
            return {"status": "unhealthy", "database": "not_initialized"}
    except Exception as e:
        return {"status": "unhealthy", "database": "disconnected", "error": str(e)}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.is_production,
        log_level="info"
    )